﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using __ts.Core.Configuration;
using __ts.Core.Utilities;

namespace CCU.Update
{

    public partial class PackageExplorer : Form
    {
        private static int pageNum = 1;
        private static int pageSize = 15;
        private static int total = 0;
        private static string url = null;
        private static int startNum
        {
            get
            {
                return (pageNum - 1) * pageSize + 1;
            }
        }
        private static int endNum
        {
            get
            {
                return (startNum + pageSize - 1) > total ? total : startNum + pageSize - 1;
            }
        }
        public static IList<string> Installeds
        {
            get
            {
                IList<string> ids = new List<string>();
                FileInfo[] fs = new DirectoryInfo(Util.RootPath + "\\Plugins").GetFiles("*.dll", SearchOption.AllDirectories);
                if (fs != null && fs.Length > 0)
                {
                    for (int i = 0; i < fs.Length; i++)
                        ids.Add(Path.GetFileNameWithoutExtension(fs[i].Name));
                }
                return ids;
            }
        }
        public PackageExplorer()
        {
            InitializeComponent();
        }

        private void PackageExplorer_Load(object sender, EventArgs e)
        {
            url = ConfigManager.GlobalAppSettings["PackageStore"];
            cbUrl.Text = url;
            load();
        }

        private void listView1_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            ListView lv = sender as ListView;

            if (e.NewValue == CheckState.Checked)
            {
                lv.Items[e.Index].BackColor = Color.MistyRose;
            }
            else
            {
                lv.Items[e.Index].BackColor = Color.White;
            }
        }

        private void listView1_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            ListView lv = sender as ListView;
            if (lv.CheckedItems.Count > 0)
            {
                btnInstall.Enabled = btnCancel.Enabled = true;
            }
            else
            {
                btnInstall.Enabled = btnCancel.Enabled = false;
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem m in listView1.CheckedItems)
            {
                m.Checked = false;
            }
        }

        private void btnReload_Click(object sender, EventArgs e)
        {
            url = cbUrl.Text.Trim();
            pageNum = 1;
            load();
        }

        private void load()
        {
            IList<string> installeds = Installeds;
            listView1.Items.Clear();
            Packages pks = new Packages(url, pageNum, pageSize);
            foreach (KeyValuePair<string, PackageInfo> objKVP in pks)
            {
                PackageInfo p = objKVP.Value;
                ListViewItem it = null;
                if (installeds.Contains(p.id))
                {
                    it = new ListViewItem(new string[] { p.id, p.version, p.description, p.authors, p.size + "KB", p.publishTime, "installed",p.md5 });
                    it.ForeColor = Color.Green;
                }
                else
                {
                    it = new ListViewItem(new string[] { p.id, p.version, p.description, p.authors, p.size + "KB", p.publishTime, "", p.md5 });
                }
                listView1.Items.Add(it);
            }

            if (pks.Count > 0)
            {
                total = pks.total;
                lbCounter.Text = string.Format("{0} to {1} of {2}", startNum, endNum, total);

                btnSwith(0);
                if (startNum <= 1)
                {
                    btnSwith(1);
                }
                if (endNum == total)
                {
                    btnSwith(2);
                }
            }
        }

        private void btnLeftMax_Click(object sender, EventArgs e)
        {
            pageNum = 1;
            load();
        }

        private void btnRightMax_Click(object sender, EventArgs e)
        {
            int totalPage = total % 15 == 0 ? (total / 15) : (total / 15 + 1);
            pageNum = totalPage;
            load();
        }

        private void btnLeftup_Click(object sender, EventArgs e)
        {
            pageNum = --pageNum < 1 ? 1 : pageNum;
            load();
        }

        private void btnRightup_Click(object sender, EventArgs e)
        {
            ++pageNum;
            load();
        }

        private void btnSwith(int code)
        {
            switch (code)
            {
                case 0:
                    btnLeftMax.Enabled = true;
                    btnLeftup.Enabled = true;
                    btnRightup.Enabled = true;
                    btnRightMax.Enabled = true;
                    break;
                case 1:
                    btnLeftMax.Enabled = false;
                    btnLeftup.Enabled = false;
                    break;
                case 2:
                    btnRightup.Enabled = false;
                    btnRightMax.Enabled = false;
                    break;
            }
        }

        private void btnInstall_Click(object sender, EventArgs e)
        {
            Dictionary<string, DownloadPackageInfo> downloadList = new Dictionary<string, DownloadPackageInfo>();
            string flowId = Guid.NewGuid().ToString();

            for (int i = 0; i < listView1.CheckedItems.Count; i++)
            {
                ListViewItem.ListViewSubItemCollection lvs = listView1.CheckedItems[i].SubItems;
                downloadList.Add(lvs[0].Text, new DownloadPackageInfo()
                {
                    id = lvs[0].Text,
                    version = lvs[1].Text,
                    description = lvs[2].Text,
                    authors = lvs[3].Text,
                    size = lvs[4].Text,
                    publishTime = lvs[5].Text,
                    installed = (string.IsNullOrEmpty(lvs[6].Text)) ? false : true,
                    md5 = lvs[7].Text
                });
            }
            Program.update(flowId, downloadList, false);
        }
    }
}
